#include "normalize.h"
#include <QStringList>
#include <QVariant>
#include "vertex.h"

NormalizePlugin::NormalizePlugin()
{
    qtd = 0;
    max = 0.0;
}


QStringList NormalizePlugin::perVertexPlugins()const
{
    QStringList st;
    st.append(QString("Mesh Normalize"));
    return st;
}

QList< QPair<QString, DataType> > NormalizePlugin::attributes(const QString& plugin) const
{
    QList< QPair<QString, DataType> > list;
    list.append( qMakePair(QString("null"), Float) );
    list.append( qMakePair(QString("null"), Float) );
    list.append( qMakePair(QString("geometry"), Vec3) );
    return list;
}

QList<QVariant> NormalizePlugin::attributeValue(const QString& plugin, int attIndex, const heds::Vertex *vertex)
{
    QList<QVariant> list;

    if(attIndex == 0)
    {
        center += vertex->geometry().toVector3DAffine();
        qtd++;
        return list;
    }else if(attIndex == 1)
    {
        QVector3D vec = vertex->geometry().toVector3DAffine() - center;
        if(vec.length() > max)
            max = vec.length();
        return list;
    }else
    {
        QVector3D position = (vertex->geometry().toVector3DAffine() - center)*(max);

        list.append(QVariant(position.x()));
        list.append(QVariant(position.y()));
        list.append(QVariant(position.z()));

        return list;
    }
}

void NormalizePlugin::endOfVertices(const QString& plugin, int attIndex)
{
    if(attIndex == 0)
    {
        center = center*(1.0/qtd);
    }
    else if( attIndex == 1)
    {
        max = (1.0/max);
    }else
    {
        center = QVector3D();
        qtd = 0;
        max = 0.0;
    }
}

Q_EXPORT_PLUGIN2(normalizePlugin, NormalizePlugin)
